<template>
  <div class="container" :style="imgStyle">
       <div class="login-wrapper" key="2">
        <div class="header">Login</div>
        <div class="rigister">
          <router-link :to="{ name: 'register' }">没有账号？去注册</router-link>
        </div>
        <div class="form-wrapper" @keyup.enter="login(loginEmail)">
          <input
            type="tel"
            name="tel"
            placeholder="请输入正确的邮箱 "
            class="input-item"
            :class="border1"
            v-model="loginEmail.email"
            @blur="checked2"
            v-show="isShow"
          />
          <input
            type="password"
            name="password"
            placeholder="请输入密码"
            class="input-item"
            :class="border"
            v-model="loginEmail.password"
            @blur="checked0"
          />
          <input
            type="tel"
            name="tel"
            placeholder=" 请输入手机号"
            class="input-item"
            :class="border1"
            v-model="loginEmail.telephone"
            @blur="checked1"
            v-show="!isShow"
          />
          <input
            type="text"
            name="tel"
            placeholder="请输入验证码"
            v-model="loginEmail.code"
            class="input-code"
          />
          <button
            class="input-btn"
            :disabled="!disabledCodeBtn || !loginEmail.email"
            @click="Sendcode(loginEmail.email)"
          >
            {{ codeText }}
          </button>
          <p class="input-pwd">
            <input type="checkbox" v-model="checked" name="" id="" />记住密码
            <!-- <span
              ><router-link :to="{ name: 'forgetLogin' }"
                >忘记密码？</router-link
              ></span
            > -->
            <span
              ><a href="javascript:;" @click="formationLogin()"
                >忘记密码</a
              ></span
            >
          </p>
          <div id="login" class="btn" @click="login(loginEmail)">Login</div>
        </div>
        <div class="msg" v-show="isShow" @click="LoginCheck()">手机号登录</div>
        <div class="msg" v-show="!isShow" @click="LoginCheck()">邮箱登录</div>
        <div class="massage" :class="masgs">
          <span>{{ massage }}</span>
        </div>
      </div>
    <!-- 弹框提示登录错误信息  -->
    <alter-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <span>{{ alterMsg }}</span>
      <span slot="footer" class="dialog-footer">
        <alter-button @click="centerDialogVisible = false">取 消</alter-button>
        <alter-button type="primary" @click="centerDialogVisible = false"
          >确 定</alter-button
        >
      </span>
    </alter-dialog>
    <!-- 忘记密码弹框 -->
    <div class="delayBackground" v-show="visible">
      <formationLogin :visible.sync="visible"></formationLogin>
    </div>
  </div>
</template>

<script>
import qs from "qs";
import "animate.css";
const Base64 = require("js-base64").Base64;
import formationLogin from "../ordinaryuser/forgetLogin.vue";
export default {
  name: "Login",
  components: { formationLogin },
  provide() {
    return {
      reload: this.reload,
    };
  },
  data() {
    return {
      imgStyle: {
        backgroundImage: `url(${require("@/assets/images/rbgc.jpg")})`,
      },
      isShow: true,
      loginEmail: {
        password: "",
        code: "",
        email: "",
        telephone: "",
        checkedcode: "",
      },
      border: "right",
      border1: "right",
      massage: "",
      masgs: "",
      codeText: "发送验证码",
      disabledCodeBtn: true,
      checked: false,
      centerDialogVisible: false,
      alterMsg: "",
      //忘记密码
      visible: false,
    };
  },
  methods: {
    //局部刷洗
    reload() {
      this.isRouterAlive = false;
      this.$nextTick(function () {
        this.isRouterAlive = true;
      });
    },
    //密码验证
    checked0() {
      // 至少4-10个字符，至少1个大写字母，1个小写字母和1个数字，其他可以是任意字符：
      // const rg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{4,10}$/;
      const rg = /[0-9]/;
      if (this.loginEmail.password === "") {
        this.massage = "密码不能为空!";
        this.border = "error";
        this.masgs = "iconfont icon-cuowuguanbiquxiao-yuankuang";
      } else if (!rg.test(this.loginEmail.password)) {
        this.masgs = "iconfont icon-cuowuguanbiquxiao-yuankuang";
        this.massage = "密码格式不正确！";
        this.border = "error";
      } else {
        this.border = "right";
        this.masgs = " ";
        this.massage = " ";
      }
    },
    //手机号验证
    checked1() {
      const rg1 = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!rg1.test(this.loginEmail.telephone)) {
        this.border1 = "right";
        this.masgs = " ";
        this.massage = " ";
      } else {
        this.masgs = "iconfont icon-cuowuguanbiquxiao-yuankuang";
        this.massage = "手机号格式不正确！";
        this.border1 = "error";
      }
    },
    //邮箱验证
    checked2() {
      const rg2 =
        /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/;
      if (!rg2.test(this.loginEmail.email)) {
        this.masgs = "iconfont icon-cuowuguanbiquxiao-yuankuang";
        this.massage = "邮箱格式不正确！";
        this.border1 = "error";
      } else {
        this.border1 = "right";
        this.masgs = " ";
        this.massage = " ";
      }
    },
    //验证码倒计时方法
    countDown(time) {
      if (time === 0) {
        this.disabledCodeBtn = true;
        this.codeText = "发送验证码";
        return;
      } else {
        this.disabledCodeBtn = false;
        this.codeText = "重新发送(" + time + ")";
        time--;
      }
      setTimeout(() => {
        this.countDown(time);
      }, 1000);
    },
    /* 发送验证码 */
    Sendcode(value) {
      this.$http({
        url: `user/sendCodeByEmail?email=${value}`,
        method: "get",
      }).then(({ data }) => {
        if (data.flag) {
          this.countDown(60);
        }
      });
    },
    // 实现登录
    login(value) {
      //首次判断是否为空
      let obj = {};
      for (let i in value) {
        if (value[i]) {
          obj[i] = value[i];
        }
      }
      if (this.loginEmail.email === "" && this.loginEmail.password === "") {
        this.centerDialogVisible = true;
        this.alterMsg = "请输入有效的信息";
      } else {
        // 是否记住密码;
        if (this.checked) {
          let password = Base64.encode(this.loginEmail.password);
          localStorage.setItem("email", this.loginEmail.email);
          localStorage.setItem("password", password);
        } else {
          localStorage.removeItem("email");
          localStorage.removeItem("password");
        }
        /* 发起登录请求 */
        this.$http({
          url: "user/loginByEmail",
          method: "post",
          data: qs.stringify(obj),
        }).then(({ data }) => {
          if (data.flag) {
            this.announceSelect(data.data[0].id);
            //将token存放到本地
            window.localStorage.setItem("token", data.data[2]);
            //成功后跳转的页面
            if (data.data[0].id === 1) {
              this.$router.push({ path: "/TeacherLogin" });
            } else {
              this.$store.commit("LoginData/LOGIN", data.data);
              this.$router.push({ path: "/Ordinaryuser" });
            }
          } else {
            this.centerDialogVisible = true;
            this.alterMsg = data.errorMsg;
          }
        });
      }
    },
    // 获取通告信息来通知websokte的连接
    announceSelect(id) {
      // 通告
      this.$http({
        method: "post",
        url: `user/getMessage?id=${id}`,
      }).then(({ data }) => {
        if (data.flag) {
          if (data.data.length != 0) {
            let arr = data.data;
            let arry = [];
            arr.forEach((item) => {
              if (item.beSend == "已发送") {
                arry.push(item.beSend);
              }
              if (item.beSend == "未发送") {
                this.websocket(item.managerName, item);
              }
            });
            if (arry.length === arr.length) {
              this.websocket(id);
            }
          } else {
            this.websocket(id);
          }
        } else {
          console.log(data.data);
        }
      });
    },
    //websoket
    websocket(userno, item) {
      let websocket = null;
      let that = this;
      if ("WebSocket" in window) {
        websocket = new WebSocket(
          "ws://124.71.219.15:8083//management_system/websocket/" + userno
        );
      } else {
        alert("当前浏览器 Not support websocket");
      }
      //连接发生错误的回调方法
      websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
      };

      //连接成功建立的回调方法
      websocket.onopen = function () {
        setMessageInnerHTML("WebSocket连接成功");
      };

      //接收到消息的回调方法
      websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
      };

      //连接关闭的回调方法
      websocket.onclose = function () {
        setMessageInnerHTML("WebSocket连接关闭");
      };

      //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = function () {
        closeWebSocket();
      };

      //将消息显示在网页上
      function setMessageInnerHTML(sendMessage) {
         if (sendMessage != "WebSocket连接成功") {
          that.HandMessage(sendMessage);
         }
      }
      // //发消息
      if (item && item.beSend == "未发送" && websocket.readyState === 1) {
        let data = item.date + "|" + item.content + "|" + item.userId;
        websocket.send(data);
        this.$http({
          method: "post",
          url: `message/updateMessageStatus?id=${item.userId}&newsId=${item.newsId}`,
        }).then(({ data }) => {
          if (data.flag) {
          } else {
            console.log(data);
          }
        });
      }
      //关闭WebSocket连接
      function closeWebSocket() {
        websocket.close();
      }
    },
    //消息提示
    HandMessage(informone) {
      const h = this.$createElement;
      this.$notify({
        title: "有新的通知",
        message: h("i", { style: "color:teal" }, "请到首页查看你的新通知"),
      });
    },
    //登录切换
    LoginCheck() {
      this.isShow = !this.isShow;
      for (let i in this.loginEmail) {
        this.loginEmail[i] = "";
      }
    },
    //忘记密码
    formationLogin() {
      this.visible = true;
    },
  },
  // 页面挂载的时候判断本地缓存是否有用户名以及密码
  mounted() {
    let strPass = localStorage.getItem("password");
    if (strPass) {
      this.loginEmail.password = Base64.decode(
        localStorage.getItem("password")
      );
      this.loginEmail.email = localStorage.getItem("email");
      this.checked = true;
    }
  },
};
</script>

<style lang="less" scoped>
.icon {
  position: absolute;
  top: 35px;
  left: 150px;
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
.right {
  border: 1px solid #807d7d;
}
.error {
  border: 1px solid red;
}
.massage {
  color: red;
  font-size: 10px;
  text-align: center;
  margin-top: 10px;
}
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  // background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);
  // background: url("@/assets/images/beijing.jpeg");
}
.login-wrapper {
  background-color: rgba(255, 255, 255, 0.7);
  width: 360px;
  height: 450px;
  padding: 0 50px;
  position: relative;
  // left: 50%;
  border-radius: 15px;
  // top: 50%;
  // -ms-transform: translateY(-50%);
  // -webkit-transform: translateY(-50%);
  // -moz-transform: translateY(-50%);
  // -o-transform: translateY(-50%);
  // transform: translate(-50%, -50%);
}
.login-wrapper .header {
  font-size: 30px;
  font-weight: bold;
  text-align: center;
  line-height: 100px;
}
.login-wrapper .rigister {
  position: absolute;
  font-size: 8px;
  top: 30px;
  right: 20px;
  color: red;
}
.login-wrapper .form-wrapper .input-item {
  display: block;
  width: 94%;
  margin-bottom: 20px;
  padding: 10px;
  font-size: 15px;
  border-radius: 20px;
  outline: none;
}
.login-wrapper .input-code {
  display: inline-block;
  width: 200px;
  font-size: 15px;
  padding: 10px;
  border: 1px solid #807d7d;
  border-radius: 20px;
}
.input-btn {
  padding: 9px;
  border: 1px solid #807d7d;
  font-size: 13px;
  border-radius: 20px;
  background-color: skyblue;
  margin-left: 30px;
}
.input-pwd {
  margin-top: 20px;
  font-size: 10px;
}
.input-pwd input {
  vertical-align: top;
}
.input-pwd span {
  margin-left: 218px;
}
.login-wrapper .form-wrapper .btn {
  width: 96%;
  text-align: center;
  padding: 5px;
  margin-top: 30px;
  background-color: rgb(103, 118, 233);
  // background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);
  color: #fff;
  border-radius: 20px;
  cursor: pointer;
}
.login-wrapper .msg {
  text-align: center;
  margin-top: 20px;
  font-size: 10px;
}
.delayBackground {
  position: absolute;

  top: 0;

  left: 0;

  width: 100%;

  height: 100%;

  z-index: 98;

  background-color: rgba(0, 0, 0, 0.5);
}
</style>